/// <reference path="../../index.d.ts" />
const Service = require("egg").Service
const path = require("path")
let help = require("../extend/helper")
class Server extends Service {
	constructor(ctx) {
		super(ctx)
		this.serverConfig = this.config.serverConfig
		this.Address = this.ctx.model.Address
	}
	checkImgPath(imgpath) {
		let fullPath = path.join(this.serverConfig.imgServerPath, imgpath)
		if (!fullPath.startsWith(this.serverConfig.uploadPath)) {
			return false
		}
		return fullPath
	}
	getCurrentIpInt() {// 保存IP 地址信息,获取地址
		let ip = this.ctx.get("X-Real-IP")
		if (ip) {
			try {
				let intip = help.ipV4toInt(ip)
				return intip
			} catch (error) {
				return 0
			}
		}
	}
	/**
 * 
 * @param {number[]} ips 
 */
	async getIps(ips) {
		let ipMap = {}
		if (ips.length == 0) {
			return ipMap
		}
		let redisKey = ips.map(v => "ip." + v)
		// redisKey = Array.from()
		let data = await this.ctx.app.redis.mget(redisKey)
		if (Array.isArray(data)) {
			data.forEach((v, index) => {
				if (v) {
					try {
						v = JSON.parse(v)
						ipMap[ips[index]] = v.country + "-" + v.province + "-" + v.city
					}
					catch (e) {
						this.ctx.logger.warn("redis存在脏数据:" + v)
					}
				}
			})
			ips = ips.filter((v, index) => {
				return !data[index]
			})
		}
		let address = await this.Address.findAll({
			where: {
				ip: {
					$in: ips
				}
			}
		})
		address.forEach((v) => {
			ipMap[v.ip] = v.country + "-" + v.region + "-" + v.city//debug
		})
		console.log(ipMap)
		return ipMap
	}

}
module.exports = Server